#encoding=utf8
'''
Created on Jan 8, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from django.contrib import admin
from app_info.models import App, AppVersion
from prj_tracker.models import EmptyModel
from django.contrib.auth.models import User
from utils import field
from django.core.exceptions import PermissionDenied
import settings
from django.contrib.admin.filters import SimpleListFilter
from sub_info.models import SubInfo


class EndYearListFilter(SimpleListFilter):
    title = 'Submitted at Year'
    parameter_name = 's_year'

    def lookups(self, request, model_admin):
        return tuple(list(set([(y.year, y.year)
            for y in AppVersion.objects.exclude(date_submitted=None).values_list('date_submitted', flat=True)])))

    def queryset(self, request, queryset):
        if self.value():
            return queryset.exclude(date_submitted=None).filter(date_submitted__year=self.value())
        return queryset


class EndMonthListFilter(SimpleListFilter):
    title = 'Submitted at Month'
    parameter_name = 's_month'

    def lookups(self, request, model_admin):
        return tuple([(m, m) for m in range(1, 13)])

    def queryset(self, request, queryset):
        if self.value():
            return queryset.exclude(date_submitted=None).filter(date_submitted__month=self.value())
        return queryset


class YearListFilter(SimpleListFilter):
    title = 'Started at Year'
    parameter_name = 'year'

    def lookups(self, request, model_admin):
        return tuple(list(set([(y.year, y.year)
            for y in AppVersion.objects.values_list('create_time', flat=True)])))

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(create_time__year=self.value())
        return queryset


class MonthListFilter(SimpleListFilter):
    title = 'Started at Month'
    parameter_name = 'month'

    def lookups(self, request, model_admin):
        return tuple([(m, m) for m in range(1, 13)])

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(create_time__month=self.value())
        return queryset


class DayListFilter(SimpleListFilter):
    title = 'Started at Day'
    parameter_name = 'day'

    def lookups(self, request, model_admin):
        return tuple([(d, d) for d in range(1, 32)])

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(create_time__day=self.value())
        return queryset


class AppVersionAdmin(admin.ModelAdmin):
    list_display = ('get_status', 'get_log_id', 'get_prj_code', 'get_app_name', 'type',
        'code', 'get_app_store', 'get_studio', 'get_product_owner',
        'get_project_coordinator',
        'get_create_date', 'get_submitted_date',
        'get_sub_info', 'get_sub_info_review_status', 'get_release_date')
    list_per_page = 20
    list_filter = ('type', 'app__app_store', 'app__studio', 'status', 'prd_team',
        YearListFilter, MonthListFilter, EndYearListFilter, EndMonthListFilter)
    search_fields = ('app__prj_code', 'app__app_name')
    change_list_template = 'changelist.html'
    list_display_links = ('get_log_id',)

    @field('Date Released')
    def get_release_date(self, obj):
        return obj.get_release_date()

    @field('Submission Request', allow_tags=True)
    def get_sub_info(self, obj, display=True):
        sub_info = SubInfo.objects.filter(app=obj.app, version=obj.code,
            validation='V')[:1]
        if display:
            if sub_info:
                status = sub_info[0].get_status_display()
                return "<a href='/admin/sub_info/subinfo/%s/' target='_blank'>%s</a> %s" %\
                    (sub_info[0].pk, sub_info[0].request_id, status)
            return ''
        return sub_info[0] if sub_info else None

    @field('Review Status')
    def get_sub_info_review_status(self, obj):
        sub_info = self.get_sub_info(obj, False)
        return sub_info.get_review_status_display() if sub_info else ''

    @field('Production Status', allow_tags=True, admin_order_field='status')
    def get_status(self, obj):
        if obj.status == 'I':
            cls = 'label-warning'
        elif obj.status == 'C':
            cls = ''
        elif obj.status == 'S':
            cls = 'label-success'
        elif obj.status == 'L':
            cls = 'label-info'
        elif obj.status == 'O':
            cls = ''
        else:
            cls = 'label-info'
        return "<span class='label %s' style='width: 65px;'><center>%s</center></span>" % (cls, obj.get_status_display())

    @field('Project', allow_tags=True)
    def get_project(self, obj):
        project = obj.project_set.all()[:1]
        if project:
            return "<a target='_blank' href='/admin/prd_order/project/%s/'>%s</a>" % (project[0].pk, project[0])
        return ''

    @field('Production Task ID', allow_tags=True, admin_order_field='log_id')
    def get_log_id(self, obj):
        return "<a href='/admin/app_info/app/%s/#version' target='_blank'>%s</a>" %\
            (obj.app.pk, obj.log_id)

    @field('App Code', admin_order_field='app__prj_code')
    def get_prj_code(self, obj):
        return obj.app.prj_code

    @field('App Name (Production)', admin_order_field='app__app_name')
    def get_app_name(self, obj):
        return obj.app.app_name

    @field('App Store', admin_order_field='app__app_store', allow_tags=True)
    def get_app_store(self, obj):
        return obj.app.get_app_store_icon()

    @field('Publish Studio', admin_order_field='app__studio')
    def get_studio(self, obj):
        return obj.app.studio

    @field('Product Owner', allow_tags=True, admin_order_field='product_owner')
    def get_product_owner(self, obj):
        if not obj.product_owner:
            return '---'
        else:
            if not obj.product_owner == 'imported':
                res = []
                for x in obj.product_owner.strip(',').split(','):
                    name = x.split(' - ')
                    if len(name) == 2:
                        res.append(name[1])
                return '<br />'.join(res)
            return obj.product_owner
#        rtn = '---'
#        if obj.product_owner:
#            try:
#                owner = User.objects.get(id=obj.product_owner)
#                rtn = owner.username
#            except User.DoesNotExist:
#                pass
#        return rtn

    @field('Project Coordinator', admin_order_field='owner')
    def get_project_coordinator(self, obj):
        rtn = "unknown"
        if obj.owner:
            try:
                owner = User.objects.get(id=obj.owner)
                rtn = owner.username
            except User.DoesNotExist:
                pass
        return rtn

    @field('Front-end Engineer', admin_order_field='programmer')
    def get_programmer(self, obj):
        return obj.programmer or "unassigned"

    @field('Date Started', admin_order_field='create_time')
    def get_create_date(self, obj):
        if obj.editor == 'imported@smalltreemedia.com':
            return '--'
        return obj.create_time.date()

    @field('Date Submitted', admin_order_field='date_submitted')
    def get_submitted_date(self, obj):
        return obj.date_submitted or ''

    def get_actions(self, request):
        """
        remove delete action
        """
        actions = super(AppVersionAdmin, self).get_actions(request)
        if actions.get('delete_selected'):
            del actions['delete_selected']
        return actions

    def changelist_view(self, request, extra_context=None):
        extra_context = {'app_label': settings.APP_LABEL_LOCAL.get('prj_tracker')}
        return admin.ModelAdmin.changelist_view(self, request, extra_context=extra_context)

    def has_add_permission(self, request):
        return False

    def change_view(self, request, object_id, form_url='', extra_context=None):
        raise PermissionDenied

    def queryset(self, request):
        qs = admin.ModelAdmin.queryset(self, request)

        if request.user.is_superuser:
            qs = admin.ModelAdmin.queryset(self, request)
        else:
            company = []
            for group in request.user.groups.all():
                if group.permissions.filter(codename__in=['add_app', 'change_app']).exists():
                    company.append(group.companygroup.company.id)
            apps = App.objects.filter(company__in=company)
            qs = AppVersion.objects.filter(app__in=apps)
        imported = qs.filter(editor='imported@smalltreemedia.com').values_list('pk', flat=True)
        no_imported = qs.exclude(editor='imported@smalltreemedia.com').values_list('pk', flat=True)
        data_list = list(no_imported) + list(imported)
        clauses = ' '.join(['WHEN %s.id=%s THEN %s' % (self.opts.db_table, pk, i) for i, pk in enumerate(data_list)])
        ordering = 'CASE %s END' % clauses
        qs = qs.filter(id__in=data_list).extra(select={'ordering': ordering}).order_by('-log_id', 'ordering')
        return qs


admin.site.register(AppVersion, AppVersionAdmin)
admin.site.register(EmptyModel)  # if I don't register an empty model, I'll never get prj_tracker display in admin
